<?php

namespace App\Support\Traits;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

trait ApiControllerTrait
{

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $list = $this->service->cursor();
        if (property_exists($this, 'resource')) {
            /**
             * @var JsonResource $resource
             */
            return $this->success($resource::collection($list));
        }

        return $this->success($list);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $info = $this->service->create($request->all());
        if (property_exists($this, 'resource')) {
            /**
             * @var JsonResource $resource
             */
            return $this->success($this->resource::make($info));
        }
        return $this->success($info);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $info = $this->service->update($id, $request->all());
        if (property_exists($this, 'resource')) {
            /**
             * @var JsonResource $resource
             */
            return $this->success($this->resource::make($info));
        }
        return $this->success($info);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $this->service->delete($id);

        return $this->ok();
    }
}